package models

import (
	"database/sql"
	"fmt"
	"log"
)

// Cart 结构体表示购物车，包含用户ID和总金额
type Cart struct {
    UserID      int     `json:"user_id"`        // 用户ID
    TotalAmount float64 `json:"total_amount"`   // 购物车总金额
}

// CartItem 结构体表示购物车中的商品
type CartItem struct {
    CartID      int     `json:"cart_id"`        // 购物车ID
    ProductID   int     `json:"product_id"`     // 商品ID

    ProductName string  `json:"productname"`    // 商品名称
    ImageURL    string  `json:"image_url"`      // 商品图片URL
    Quantity    int     `json:"quantity"`       // 商品数量
    Price       float64 `json:"price"`          // 商品单价
    Status      string  `json:"status"`         // 商品状态
}

// 向购物车中添加商品
func AddToCart(userID int, productID int, quantity int) (int64, error) {
    var cartID int

    // 首先检查用户是否存在
    _, err := GetUserByID(userID)
    if err != nil {
        return 0, fmt.Errorf("用户不存在")
    }

    // 检查商品是否存在并获取价格
    product, err := GetProductByID(productID)
    if err != nil {
        return 0, err
    }
    if product.ID == 0 {
        return 0, fmt.Errorf("商品不存在")
    }

    // 开启事务
    tx, err := db.Begin()
    if err != nil {
        return 0, err
    }
    defer tx.Rollback()

    // 检查购物车是否存在，如果不存在则创建
    err = tx.QueryRow("SELECT user_id FROM carts WHERE user_id = ?", userID).Scan(&cartID)
    if err != nil {
        if err == sql.ErrNoRows {
            // 创建新的购物车
            _, err = tx.Exec("INSERT INTO carts (user_id, total_amount) VALUES (?, 0)", userID)
            if err != nil {
                return 0, err
            }
            cartID = userID
        } else {
            return 0, err
        }
    }

    // 检查商品是否已存在于购物车中
    var existingQuantity int
    // 感觉这个SELECT是要选出下面操作中要更改的部分
    err = tx.QueryRow("SELECT quantity, status FROM cart_items WHERE cart_id = ? AND product_id = ?", cartID, productID).Scan(&existingQuantity)
    if err != nil {
        if err == sql.ErrNoRows {
            // 商品不存在于购物车中，插入新记录
            _, err = tx.Exec(
                "INSERT INTO cart_items(cart_id, product_id, price, quantity, status) VALUES(?, ?, ?, ?, ?)",
                cartID, productID, product.Price, quantity, "未支付",
            )
            if err != nil {
                return 0, err
            }
        } else {
            // 商品已存在，更新数量和状态
            _, err = tx.Exec(
                "UPDATE cart_items SET quantity = quantity + ?, status = ? WHERE cart_id = ? AND product_id = ?",
                quantity, "未支付", cartID, productID,
            )
            if err != nil {
                return 0, err
            }
        }
    } 

    // 更新购物车总金额
    _, err = tx.Exec(`
        UPDATE carts 
        SET total_amount = (
            SELECT SUM(quantity * price) 
            FROM cart_items 
            WHERE cart_id = ?
        )
        WHERE user_id = ?
    `, cartID, userID)
    if err != nil {
        return 0, err
    }

    // 提交事务
    if err = tx.Commit(); err != nil {
        return 0, err
    }

    return int64(cartID), nil
}

// 获取指定用户ID的购物车信息，并计算总金额
func GetCartByUserID(userID int) (Cart, []CartItem, error) {
    var cart Cart
    // 获取购物车基本信息
    err := db.QueryRow("SELECT user_id, total_amount FROM carts WHERE user_id = ?", userID).
        Scan(&cart.UserID, &cart.TotalAmount)
    if err != nil {
        if err == sql.ErrNoRows {
            // 如果购物车不存在，创建一个新的购物车
            _, err = db.Exec("INSERT INTO carts(user_id, total_amount) VALUES(?, 0)", userID)
            if err != nil {
                return cart, nil, err
            }
            cart.UserID = userID
            cart.TotalAmount = 0
            return cart, []CartItem{}, nil
        }
        return cart, nil, err
    }

    // 获取购物车中的商品信息
    rows, err := db.Query(`
        SELECT ci.cart_id, ci.product_id, ci.quantity, ci.price, ci.status,
               p.productname, p.image_url
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.cart_id = ?`, userID)
    if err != nil {
        return cart, nil, err
    }
    defer rows.Close()

    var cartItems []CartItem
    for rows.Next() {
        var item CartItem
        var productName, imageURL string
        err := rows.Scan(
            &item.CartID, &item.ProductID, &item.Quantity, &item.Price, &item.Status,
            &productName, &imageURL)
        if err != nil {
            return cart, nil, err
        }
        item.ProductName = productName
        item.ImageURL = imageURL
        cartItems = append(cartItems, item)
    }

    // 重新计算总金额以确保准确性
    var totalAmount float64
    for _, item := range cartItems {
        totalAmount += item.Price * float64(item.Quantity)
    }
    cart.TotalAmount = totalAmount

    // 更新数据库中的总金额
    _, err = db.Exec("UPDATE carts SET total_amount = ? WHERE user_id = ?", totalAmount, userID)
    if err != nil {
        return cart, nil, err
    }

    return cart, cartItems, nil
}

// 更新购物车的总金额
func UpdateTotalAmount(cartID int) error {
    // 计算购物车的总金额
    var totalAmount float64
    rows, err := db.Query("SELECT quantity, price FROM cart_items WHERE cart_id = ?", cartID)
    if err != nil {
        log.Println("Error fetching cart items to update total amount:", err)
        return err
    }
    defer rows.Close()

    // 计算总金额
    for rows.Next() {
        var quantity int
        var price float64
        err := rows.Scan(&quantity, &price)
        if err != nil {
            log.Println("Error scanning cart item:", err)
            return err
        }
        totalAmount += float64(quantity) * price
    }

    // 更新购物车总金额
    stmt, err := db.Prepare("UPDATE carts SET total_amount = ? WHERE user_id = ?")
    if err != nil {
        log.Println("Error preparing statement to update total amount:", err)
        return err
    }
    defer stmt.Close()

    _, err = stmt.Exec(totalAmount, cartID)
    if err != nil {
        log.Println("Error executing statement to update total amount:", err)
        return err
    }

    return nil
}

// 从购物车中删除商品
func DeleteFromCart(userID int, productID int) (int64, error) {
    // 开启事务
    tx, err := db.Begin()
    if err != nil {
        return 0, fmt.Errorf("开启事务失败: %v", err)
    }
    defer tx.Rollback()

    // 删除购物车中的商品
    result, err := tx.Exec("DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?", 
        userID, productID)
    if err != nil {
        return 0, fmt.Errorf("删除商品失败: %v", err)
    }

    // 获取删除的行数
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        return 0, fmt.Errorf("获取影响行数失败: %v", err)
    }

    // 更新购物车总金额
    var totalAmount float64
    err = tx.QueryRow(`
        SELECT COALESCE(SUM(quantity * price), 0) 
        FROM cart_items 
        WHERE cart_id = ?`, userID).Scan(&totalAmount)
    if err != nil {
        return 0, fmt.Errorf("计算总金额失败: %v", err)
    }

    // 更新购物车总金额
    _, err = tx.Exec("UPDATE carts SET total_amount = ? WHERE user_id = ?", 
        totalAmount, userID)
    if err != nil {
        return 0, fmt.Errorf("更新总金额失败: %v", err)
    }

    // 提交事务
    if err = tx.Commit(); err != nil {
        return 0, fmt.Errorf("提交事务失败: %v", err)
    }

    return rowsAffected, nil
}

// UpdateCartItemQuantity 更新购物车中商品的数量
func UpdateCartItemQuantity(userID, productID, quantity int) error {
    // 检查商品是否存在于购物车中
    var exists bool
    err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM cart_items WHERE cart_id = ? AND product_id = ?)", userID, productID).Scan(&exists)
    if err != nil {
        return err
    }
    if !exists {
        return fmt.Errorf("商品不存在")
    }

    // 更新商品数量
    _, err = db.Exec("UPDATE cart_items SET quantity = ? WHERE cart_id = ? AND product_id = ?", quantity, userID, productID)
    return err
}